﻿using LightCAD.Core;
using LightCAD.Core.Elements;
using LightCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using static LightCAD.Core.Elements.LcPolyLine;

namespace LightCAD.Drawing.Actions
{

    public class RectangAction : ElementAction
    {
        public static string CommandName;
        public static LcCreateMethod[] CreateMethods;
        private List<Vector2> points;
        /// <summary>
        /// 多段线第一个点
        /// </summary>
        private Vector2? startPoint { get; set; }
        /// <summary>
        /// 每节线的开始点
        /// </summary>
        private Vector2? firstPoint { get; set; }
        /// <summary>
        /// 每节线的第二个点
        /// </summary>
        private Vector2? secondPoint { get; set; }
        /// <summary>
        /// 零时集合
        /// </summary>
        private List<PlineSegment> Segments { get; set; }


        static RectangAction()
        {

            CreateMethods = new LcCreateMethod[3];
            CreateMethods[0] = new LcCreateMethod()
            {
                Name = "CreateRectang",
                Description = "创建矩形",
                Steps = new LcCreateStep[]
                {
                    new LcCreateStep { Name=  "Step0", Options= "REXTANG指定第一个角点获[倒角(C)/标高（E）/圆角（F）/厚度（T）宽度（W）]:" },
                    new LcCreateStep { Name=  "Step1", Options= "REXTANG指定另一个角点或[面积(A)/尺寸(D)/旋转(R)]:" },

                }
            };

        }




        internal static void Initilize()
        {
            ElementActions.Rectang = new RectangAction();
            LcDocument.ElementActions.Add(BuiltinElementType.Rectang, ElementActions.Rectang);

        }

        private InElementsInputer InElementsInputer { get; set; }
        private ElementSetInputer ElementInputers { get; set; }
        private ElementInputer ElementInputer { get; set; }
        private CmdTextInputer CmdTextInputer { get; set; }
        private PointInputer PointInputer { get; set; }



        private RectangAction() { }
        public RectangAction(IDocumentEditor docEditor) : base(docEditor)
        {
            this.commandCtrl.WriteInfo("命令：RECTANG");
        }



        public async void ExecCreate(string[] args = null)
        {
            this.StartCreating();
            this.Segments = new List<PlineSegment>();
            var curMethod = CreateMethods[0];
            this.PointInputer = new PointInputer(this.docEditor);
            var step0 = curMethod.Steps[0];
            var result0 = await PointInputer.Execute(step0.Options);
            if (PointInputer.isCancelled)
            {
                this.Cancel();
                return;
            }
            this.firstPoint = (Vector2)result0.ValueX;
            var step1 = curMethod.Steps[1];
            var result1 = await PointInputer.Execute(step1.Options);
            if (PointInputer.isCancelled)
            {
                this.Cancel();
                return;
            }

            // Calculate rectangle vertices
            Vector2 topLeft = new Vector2(Math.Min(((Vector2)result0.ValueX).X, ((Vector2)result1.ValueX).X), Math.Max(((Vector2)result0.ValueX).Y, ((Vector2)result1.ValueX).Y));
            Vector2 bottomRight = new Vector2(Math.Max(((Vector2)result0.ValueX).X, ((Vector2)result1.ValueX).X), Math.Min(((Vector2)result0.ValueX).Y, ((Vector2)result1.ValueX).Y));
            Vector2 topRight = new Vector2(bottomRight.X, topLeft.Y);
            Vector2 bottomLeft = new Vector2(topLeft.X, bottomRight.Y);

            // Create rectangle segments
            PlineSegment seg1 = new PlineSegment();
            seg1.Start = topLeft;
            seg1.End = topRight;
            seg1.Type = PlineSegmentType.Line;
            Segments.Add(seg1);

            PlineSegment seg2 = new PlineSegment();
            seg2.Start = topRight;
            seg2.End = bottomRight;
            seg2.Type = PlineSegmentType.Line;
            Segments.Add(seg2);

            PlineSegment seg3 = new PlineSegment();
            seg3.Start = bottomRight;
            seg3.End = bottomLeft;
            seg3.Type = PlineSegmentType.Line;
            Segments.Add(seg3);

            PlineSegment seg4 = new PlineSegment();
            seg4.Start = bottomLeft;
            seg4.End = topLeft;
            seg4.Type = PlineSegmentType.Line;
            Segments.Add(seg4);

            CreateRectang(Segments);
            this.EndCreating();
        }

        private void CreateRectang(List<PlineSegment> segments)
        {
            if (Segments == null || Segments.Count != 4)
            {
                // 如果线段列表为空或线段数量不为4，则无法创建矩形
                return;
            }
            var doc = this.docRt.Document;
            DocumentManager.CurrentRecorder.BeginAction("PolyLine");
            var PolyLine = doc.CreateObject<LcPolyLine>();
            PolyLine.IsClosed = true;

            PolyLine.Segments = Segments;

            doc.ModelSpace.InsertElement(PolyLine);
            this.docRt.Action.ClearSelects();
            DocumentManager.CurrentRecorder.EndAction();
 

        }
       
        public override void DrawAuxLines(SKCanvas canvas)
        {
            if (this.firstPoint != null)
            {
                var mp = this.vportRt.PointerMovedPosition.ToVector2d();
                var secPoint = this.vportRt.ConvertScrToWcs(mp);
                Vector2 topLeft = new Vector2(Math.Min(this.firstPoint.X, secPoint.X), Math.Max(this.firstPoint.Y, secPoint.Y));
                Vector2 bottomRight = new Vector2(Math.Max(this.firstPoint.X, secPoint.X), Math.Min(this.firstPoint.Y, secPoint.Y));
                Vector2 topRight = new Vector2(bottomRight.X, topLeft.Y);
                Vector2 bottomLeft = new Vector2(topLeft.X, bottomRight.Y);

                DrawAuxLine(canvas, topLeft, topRight, Constants.auxElementPen);
                DrawAuxLine(canvas, topRight, bottomRight, Constants.auxElementPen);
                DrawAuxLine(canvas, bottomRight, bottomLeft, Constants.auxElementPen);
                DrawAuxLine(canvas, bottomLeft, topLeft, Constants.auxElementPen);
            }
        }
        private void DrawAuxLine(SKCanvas canvas, Vector2 p0, Vector2 p1, SKPaint sKPaint)
        {
            var sk_pre = this.vportRt.ConvertWcsToScr(p0).ToSKPoint();
            var sk_p = this.vportRt.ConvertWcsToScr(p1).ToSKPoint();
            //辅助元素的颜色 
            canvas.DrawLine(sk_pre, sk_p, sKPaint);
            //辅助曲线的颜色，包括辅助长度，辅助角度等
        }





    }
}


